package com.huangsm.book.designmodel.executor.diythreadpool;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

/**
 * 定义线程类，作为任务对象
 *
 * @author huang
 * @date 2019/2/19
 */
public class MyThread implements Runnable, Comparable<MyThread> {

    private String name;

    public MyThread() {
    }

    public MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        try {
            //代表业务执行时间
            Thread.sleep(100);
            System.out.println(name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
      /*  ExecutorService executorService = Executors.newFixedThreadPool(1);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            //不使用线程池调度任务时，开启1000个以上的线程工作
            //new Thread(new MyThread("testNoThreadPool"+Integer.toString(i))).start();
            executorService.execute(new MyThread("testNoThreadPool" + Integer.toString(i)));
            //使用简单的ThreadPool线程池进行同样数量的任务调度
            // ThreadPool.getInstance().start(new MyThread("testThreadPool"+Integer.toString(i)));
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);*/

        /**
         * 使用优先队列测试
         */
        ThreadPoolExecutor exe = new ThreadPoolExecutor(100, 200, 0L, TimeUnit.SECONDS, new PriorityBlockingQueue<Runnable>());
        for (int i = 0; i < 1000; i++) {
            exe.execute(new MyThread("优先级队列测试_"+Integer.toString(999-i)));
        }
    }

    /**
     * 比较任务的优先级
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(MyThread o) {
        int me = Integer.parseInt(this.name.split("_")[1]);
        //名称中标注任务优先级
        int other = Integer.parseInt(o.name.split("_")[1]);
        if (me > other) {
            return 1;
        } else if (me < other) {
            return -1;
        } else {
            return 0;
        }
    }
}
